<template>
  <view class="detail-container">
    <!-- 商品图片轮播 -->
    <swiper class="swiper" :indicator-dots="true" :autoplay="true">
      <swiper-item v-for="(img, index) in productImages" :key="index">
        <cover-image :src="url('s', img, 'png')" mode="aspectFill" class="uni-radius-lg rounded"></cover-image>
      </swiper-item>
    </swiper>
    
    <!-- 商品信息 -->
    <view class="product-info bg-white uni-pa-5">
      <view class="d-flex justify-content-between align-items-start uni-my-3">
        <text class="product-name fs-4"> <text class="bi bi-fire text-danger"></text> {{ product?.name }}</text>
        <uni-tag text="新品" type="warning" v-if="product?.isNew" />
      </view>
      <view class="product-price text-danger mb-3">
        <text class="fs-4">¥{{ product?.price?.toFixed(2) }}</text>
      </view>
      <view class="category-info uni-mb-3">
        <text class="category-label">商品品类：</text>
        <uni-tag :text="getCategoryLabel(product?.category)" type="primary" size="small" />
      </view>
      <view class="product-desc text-muted">
        {{ product?.description }}
      </view>
     <view class="uni-my-6"> <text class="text-danger"><text class="bi bi-person-arms-up"></text>多人好评</text></view> 
    </view>
    
    <!-- 规格选择区域 -->
    <view class=" bg-white uni-my-2 uni-pa-5 ">
      <view class="specs-item" v-if="productSpecs.length">
        <text class="specs-label">规格</text>
        <view class="specs-options uni-my-5">
          <view class="radio-group">
            <view 
              v-for="spec in productSpecs" 
              :key="spec.value"
              :class="['radio-button', selectedSpec === spec.value ? 'active' : '']"
              @tap="selectSpec(spec.value)"
            >
              {{ spec.label }}
            </view>
          </view>
        </view>
      </view>
      
      <view class="quantity-item uni-my-5">
        <text class="specs-label">数量</text>
        <uni-number-box 
          v-model="quantity"
          :min="1"
          :max="99"
          class="uni-my-5"
          @change="updateTotal"
        />
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <view class="container d-flex">
        <button  type="primary" class=" w-100  flex-grow-1 uni-mr-2" @tap="showSpecsPopup">
          加入购物车
        </button>
        <button  type="warn" class=" w-100 flex-grow-1" @tap="showSpecsPopup('buy')">
          立即购买
        </button>
      </view>
    </view>

    <!-- 规格选择弹窗 -->
    <uni-popup ref="specsPopup" type="bottom">
      <view class="bg-white">
        <view class="specs-header uni-pa-5 border-bottom">
          <view class="d-flex justify-content-between ">
            <cover-image 
              :src="url('sp', store.products.findIndex(p => p.id === product?.id), 'png')"
              class="specs-image uni-mr-3"
              mode="aspectFill"
            ></cover-image>
            <view class="flex-grow-1">
              <view class="fs-4 mb-2">{{ product?.name }}</view>
              <view class="text-danger fs-4">¥{{ totalPrice }}</view>
            </view>
            <text class="bi bi-x fs-4" @tap="closeSpecsPopup"></text>
          </view>
        </view>
        
        <view class="specs-body uni-pa-5">
          <!-- 规格选择 -->
          <view class="specs-section mb-4" v-if="productSpecs.length">
            <text class="d-block mb-2">选择规格</text>
            <view class="radio-group">
              <view 
                v-for="spec in productSpecs" 
                :key="spec.value"
                :class="['radio-button', selectedSpec === spec.value ? 'active' : '']"
                @tap="selectSpec(spec.value)"
              >
                {{ spec.label }}
              </view>
            </view>
          </view>
          
          <!-- 数量选择 -->
          <view class="quantity-section">
            <text class="d-block mb-2">数量</text>
            <uni-number-box 
              v-model="quantity"
              :min="1"
              :max="99"
              @change="updateTotal"
            />
          </view>
        </view>
        
        <view class=" uni-pa-5 border-top bg-white">
          <button 
            type="warn"
            class="w-100"
            @tap="confirmAction"
          >
            {{ actionType === 'buy' ? '立即购买' : '加入购物车' }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useCounterStore } from '@/stores/counter';
import { useCartStore } from '@/stores/cartStore';

const store = useCounterStore();
const cartStore = useCartStore();
const url = $url;

// 添加品类标签映射函数
const getCategoryLabel = (category) => {
  const categoryMap = {
    'stationery': '文具',
    'accessories': '饰品',
    'clothing': '服饰',
    'daily': '生活',
    'collection': '收藏'
  };
  return categoryMap[category] || '其他';
};

const product = ref(null);
const productImages = ref([]);
const specsPopup = ref(null);
const selectedSpec = ref('');
const quantity = ref(1);
const actionType = ref('');

// 添加规格选择方法
const selectSpec = (value) => {
  selectedSpec.value = value;
  // 强制更新视图
  nextTick(() => {
    selectedSpec.value = value;
  });
};

// 计算总价
const totalPrice = computed(() => {
  if (!product.value || !product.value.price) return "0.00";
  return (product.value.price * quantity.value).toFixed(2);
});

// 更新总价的方法
const updateTotal = (value) => {
  quantity.value = value;
  console.log("数量更新:", quantity.value, "总价:", totalPrice.value);
};

// 获取商品规格
const productSpecs = computed(() => {
  if (!product.value) return [];
  
  const specialSpecs = {
    "墨枢笔记本": [
      { label: "A5", value: "a5" },
      { label: "A4", value: "a4" },
      { label: "B5", value: "b5" }
    ],
    "墨枢项链系列": [
      { label: "标准", value: "standard" },
      { label: "加长", value: "long" },
      { label: "定制", value: "custom" }
    ],
    "墨枢·物理大家盲盒": [
      { label: "单盒", value: "single" },
      { label: "整盒(5个)", value: "box" }
    ],
    "墨枢T恤": [
      { label: "S码", value: "s" },
      { label: "M码", value: "m" },
      { label: "L码", value: "l" },
      { label: "XL码", value: "xl" }
    ],
    "墨枢陶瓷马克杯": [
      { label: "350ml", value: "350ml" },
      { label: "450ml", value: "450ml" },
      { label: "定制款", value: "custom" }
    ],
    "墨枢抱枕": [
      { label: "40x40cm", value: "small" },
      { label: "45x45cm", value: "medium" },
      { label: "50x50cm", value: "large" }
    ],
    "墨枢帆布包": [
      { label: "小号", value: "small" },
      { label: "中号", value: "medium" },
      { label: "大号", value: "large" }
    ],
    "墨枢拼图": [
      { label: "300片", value: "300" },
      { label: "500片", value: "500" },
      { label: "1000片", value: "1000" }
    ]
  };
  
  return specialSpecs[product.value.name] || [];
});

// 生成商品图片数组的函数
const generateProductImages = (baseImage) => {
  const imageIndex = baseImage.match(/\d+/)?.[0]; // 提取数字
  if (!imageIndex) return [baseImage];

  // 根据不同的商品ID设置不同数量的图片
  const imageCountMap = {
    0:5,
    1: 4, // sp1: sp1-0, sp1-1, sp1-2, sp1-3
    2: 4, // sp2: sp2-0, sp2-1, sp2-2
    3: 4, // sp3: sp3-0, sp3-1, sp3-2
    4: 4, // sp4: sp4-0, sp4-1
    5: 4,  // sp5: sp5
    6:4,
    7:4,
    8:4,
    9:4,
    10:4,
    11:1,
    12:1,
    13:1,
    14:1,
    16:1,
    17:1,
  };

  const count = imageCountMap[imageIndex] || 1;
  const images = [];
  
  // 如果只有一张图片，直接返回原图
  if (count === 1) {
    return [`p${imageIndex}`];
  }

  // 生成图片数组
  for (let i = 0; i < count; i++) {
    images.push(`p${imageIndex}-${i}`);
  }
  
  return images;
};

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const id = currentPage.options.id;
  
  // 获取商品详情
  product.value = store.products.find(p => p.id === Number(id));
  if (product.value) {
    // 根据商品在列表中的索引生成图片名称
    const productIndex = store.products.findIndex(p => p.id === Number(id));
    const baseImage = `sp${productIndex }`;
    productImages.value = generateProductImages(baseImage);
  }
});

// 显示规格选择弹窗
const showSpecsPopup = (type = 'cart') => {
  actionType.value = type;
  specsPopup.value.open();
};

// 关闭规格选择弹窗
const closeSpecsPopup = () => {
  specsPopup.value.close();
};

// 确认操作
const confirmAction = async () => {
  if (productSpecs.value.length && !selectedSpec.value) {
    uni.showToast({
      title: '请选择规格',
      icon: 'none'
    });
    return;
  }
  
  const cartItem = {
    id: product.value.id,
    title: product.value.name,
    price: product.value.price,
    image: product.value.image || 'default_image', // 确保image字段存在
    quantity: quantity.value,
    specs: selectedSpec.value ? {
      规格: productSpecs.value.find(spec => spec.value === selectedSpec.value)?.label
    } : {},
    category: product.value.category || 'default', // 确保category字段存在
    total: Number(totalPrice.value)
  };
  
  console.log('即将添加到购物车的商品完整数据:', JSON.stringify(cartItem));
  
  if (actionType.value === 'buy') {
    // 直接购买模式
    try {
      // 先清空购物车
      await cartStore.clearCart();
      // 添加当前商品到购物车
      const success = await cartStore.addToCart(cartItem);
      if (!success) {
        throw new Error('添加商品失败');
      }
      // 跳转到结算页面
      uni.navigateTo({
        url: '/pages/other/cart/checkout'
      });
    } catch (error) {
      console.error('立即购买失败:', error);
      uni.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    }
  } else {
    // 加入购物车模式
    try {
      console.log('准备添加到购物车的商品数据:', cartItem);
      
      // 输出商品所有字段
      console.log('商品ID:', cartItem.id);
      console.log('商品标题:', cartItem.title);
      console.log('商品价格:', cartItem.price);
      console.log('商品图片:', cartItem.image);
      console.log('商品数量:', cartItem.quantity);
      console.log('商品规格:', cartItem.specs);
      console.log('商品分类:', cartItem.category);
      console.log('商品总价:', cartItem.total);
      
      const success = await cartStore.addToCart(cartItem);
      if (!success) {
        throw new Error('添加商品失败');
      }
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
    } catch (error) {
      console.error('加入购物车失败:', error);
      uni.showToast({
        title: error.message || '添加失败',
        icon: 'none'
      });
    }
  }
  
  closeSpecsPopup();
};
</script>

<style scoped>
.swiper {
  height: 750rpx;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.category-label {
  font-size: 28rpx;
  color: #666;
}

.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
}

.specs-popup {
  max-height: 70vh;
  border-radius: 20rpx 20rpx 0 0;
}

.specs-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
}

.specs-label {
  font-size: 28rpx;
  color: #666;
}

/* 添加自定义radio样式 */
.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.radio-button {
  padding: 16rpx 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s;
  
  &.active {
    color: var(--td-brand-color);
    border-color: var(--td-brand-color);
    background: rgba(0, 157, 255, 0.1);
  }
}
</style> 